import 'package:black_movice/api/Api.dart';
import 'package:black_movice/config/configs.dart';
import 'package:black_movice/mock/movice_list.dart';
import 'package:black_movice/models/FormModel.dart';
import 'package:black_movice/models/MoviceListModel.dart';
import 'package:black_movice/models/localModels/MovieCategory.dart';
import 'package:black_movice/utils/Utils.dart';
import 'package:black_movice/views/components/moviceCard/movice_card.dart';
import 'package:black_movice/views/components/shimmer/cu_shimmer.dart';
import 'package:buttons_tabbar/buttons_tabbar.dart';
import 'package:black_movice/net/http_client.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class Index extends StatefulWidget {
  const Index({super.key});

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {
// 创建 MovieCategory 对象列表
  List<MovieCategory> movieCategoryList = [
    MovieCategory(id: 0, categoryName: '推荐'),
    MovieCategory(id: 1, categoryName: '新剧'),
    MovieCategory(id: 2, categoryName: '短剧'),
    MovieCategory(id: 3, categoryName: '电视剧'),
    MovieCategory(id: 4, categoryName: '电影'),
    MovieCategory(id: 5, categoryName: '综艺'),
    MovieCategory(id: 6, categoryName: '动漫'),
  ];

// 顶部
  Widget moviceCategory(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 10.sp),
      width: double.infinity,
      height: 40.sp,
      child: ButtonsTabBar(
        backgroundColor: Colors.transparent,
        unselectedBackgroundColor: Colors.transparent,
        labelStyle: TextStyle(color: Colors.white),
        unselectedLabelStyle: TextStyle(color: Colors.white70),
        buttonMargin: EdgeInsets.symmetric(vertical: 0, horizontal: 5.sp),
        onTap: (p0) {
          Utils.logError(p0);
          formModel.categoryId = p0;
          setState(() {
            _loading = true;
            moviceList = [];
          });
          postMoviceList();
        },
        tabs: movieCategoryList
            .map(
              (category) => Tab(
                text: category.categoryName,
              ),
            )
            .toList(),
      ),
    );
  }

// 搜索框
  Widget seachContainer() {
    return Row(
      children: [
        // 这里是搜索框
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white30,
              borderRadius: BorderRadius.circular(10.sp),
            ),
            child: Row(
              children: [
                // 搜索图标
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8.w),
                  child: const Icon(
                    Icons.search,
                    color: Colors.white70,
                  ),
                ),
                // 剩余空白部分
                Expanded(child: Container()),
              ],
            ),
          ),
        ),
        TextButton.icon(
          onPressed: () => Utils.logDebug("点击了筛选按钮"),
          label: Text(
            "筛选",
            style:
                TextStyle(fontSize: Configs.titleSize_14, color: Colors.white),
          ),
          icon: Icon(
            Icons.filter_list, color: Colors.white, // 设置图标颜色
          ),
        )
      ],
    );
  }

// 顶部搜索框
  Widget appBar(BuildContext context) {
    // 屏幕高度
    double barHeight = MediaQuery.of(context).size.height * 0.1;
    // 获取顶部安全区的高度
    double topSafeAreaHeight = MediaQuery.of(context).padding.top;
    return Container(
      height: barHeight + topSafeAreaHeight,
      padding: EdgeInsets.only(
          top: topSafeAreaHeight,
          left: 5.sp,
          right: 5.sp,
          bottom: 10.sp), // 设置上内边距为顶部安全区的高度
      decoration: BoxDecoration(
        color: Colors.lightBlueAccent, // 设置背景色为绿色
      ),
      child: Column(
        children: [
          Expanded(child: seachContainer()),
          moviceCategory(context),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    final HttpClient httpClient = HttpClient.getInstance;
    setupMoviceListMock(httpClient);
    formModel.categoryId = movieCategoryList[0].id;
    postMoviceList();
  }

  // Loading
  late bool _loading = true;
  // 表单
  late FormModel formModel = FormModel();
  final Api _api = Api.instance;

  // 电影列表
  List<MoviceListModel> moviceList = [MoviceListModel()];
  // 获取电影列表
  void postMoviceList() async {
    setState(() {
      _loading = true;
    });

    moviceList = await _api.moviceList(formModel);
    setState(() {
      _loading = false;
    });
  }

  // 电影卡片流式布局
  Widget buildCardGrid(BuildContext context) {
    return SingleChildScrollView(
      // 滚动视图的内边距设置为零
      padding: EdgeInsets.zero,
      // 滚动视图的子组件，使用 MasonryGridView 实现交错网格布局
      child: MasonryGridView.count(
        // 网格视图的内边距，使用之前定义的 kPadding
        padding: kPadding,
        // 网格视图的列数，这里设置为 2，表示每行显示两个子元素
        crossAxisCount: 2,
        // 网格视图的子元素数量，这里设置为 8
        itemCount: moviceList.length,
        // 用于构建每个子元素的回调函数，调用 buildSkeletonItem 方法构建单个骨架屏元素
        itemBuilder: (BuildContext context, int index) => moviceList.isEmpty
            ? Center()
            : MoviceCard(movice: moviceList[index]),
        // 垂直方向上子元素之间的间距
        mainAxisSpacing: 10,
        // 水平方向上子元素之间的间距
        crossAxisSpacing: 10,
        // 滚动的物理效果，设置为禁止滚动
        physics: const NeverScrollableScrollPhysics(),
        // 是否根据子元素的大小来调整网格视图的大小，设置为 true 表示根据子元素大小调整
        shrinkWrap: true,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: movieCategoryList.length,
      child: Column(
        children: [
          appBar(context),
          Expanded(
            child: TabBarView(
              // 根据 tabTitles 长度生成对应的内容
              children: movieCategoryList
                  .map(
                    (category) => _loading
                        ? CuShimmer()
                        : GestureDetector(
                            onTap: () {
                              Utils.logDebug("打印信息");
                            },
                            child: buildCardGrid(context),
                          ),
                  )
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }
}
